
import { ElMessage } from 'element-plus';
import { AxiosError, type AxiosResponse } from 'axios';

export interface ResponseData {
  code: string;
  message?: string;
  data: any;
  timestamp?: string;
}

export type DownloadResType = ResponseData | Blob;
type ApiResType = AxiosResponse<DownloadResType> | AxiosError<DownloadResType>;

export const errorMsg = (res: ApiResType) => {
  console.log('errorMsg res', res);
  let message = '';
  if (res instanceof AxiosError) {
    message = res.message || res.code || '';
    // 处理消息换行
    if (message.indexOf('\n') === -1) {
      message = message.replace(/(.{50})/g, '$1<br/>');
    }

    ElMessage({
      dangerouslyUseHTMLString: true,
      type: 'error',
      message: `${message}`,
    });
  } else {
    // 处理 AxiosResponse 类型
    const responseData = res.data;
    if (responseData && typeof responseData === 'object' && 'code' in responseData) {
      message = responseData.message || responseData.code;
      // 处理消息换行
      if (message.indexOf('\n') === -1) {
        message = message.replace(/(.{50})/g, '$1<br/>');
      }

      ElMessage({
        dangerouslyUseHTMLString: true,
        type: 'error',
        message: `${message}`,
      });
    }
  }
};

export function download(res: AxiosResponse<DownloadResType>, name: string, format?: string) {
  const fileReader = new FileReader();
  fileReader.onload = () => {
    try {
      // 说明是普通对象数据，后台转换失败 或者为.json 文件
      const jsonData = JSON.parse(fileReader.result as string);

      // 判断 jsonData 里是否有 code, 有则说明是错误信息
      if ('code' in jsonData) {
        if (jsonData.code === '401') {
          window.microApp.setGlobalData({ code: '401' });
          return;
        }
        ElMessage({
          type: 'error',
          message: jsonData.message || jsonData.code,
        });
      } else {
        downloadFile(res, name, format);
      }
    } catch (error) {
      // 解析成对象失败，说明是正常的文件流
      downloadFile(res, name, format);
    }
  };

  if (res.data instanceof Blob) {
    fileReader.readAsText(res.data);
  }
}

export function downloadFile(res: AxiosResponse<DownloadResType>, name: string, format?: string) {
  const downloadElement = document.createElement('a');
  const suffix =
    res.headers && res.headers['content-disposition']
      ? res.headers['content-disposition'].split('=')[1].split(';')[0]
      : '';
  const filename = decodeURIComponent(suffix);
  format = suffix.split('.').pop() || format || '';

  console.log('suffix:', suffix, 'format:', format, 'filename:', filename, 'name:', name);

  if (res.data instanceof Blob) {
    const href = URL.createObjectURL(res.data);
    downloadElement.href = href;
    downloadElement.download = name ? `${name}.${format}` : filename;

    const clickEvent = new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
    });
    downloadElement.dispatchEvent(clickEvent);

    downloadElement.remove();
    URL.revokeObjectURL(href);
  }
}

export function noop(): void {}

export function timeTrans(UTCDateString: string | null): string {
  if (!UTCDateString) {
    return '-';
  }
  function formatFunc(str: number): string {
    return str > 9 ? str.toString() : '0' + str;
  }
  const date2 = new Date(UTCDateString);
  const year = date2.getFullYear();
  const mon = formatFunc(date2.getMonth() + 1);
  const day = formatFunc(date2.getDate());
  const hour = formatFunc(date2.getHours());
  const min = formatFunc(date2.getMinutes());
  const dateStr = `${year}-${mon}-${day} ${hour}:${min}`;
  return dateStr;
}

export function dateTrans() {
  const date2 = new Date();
  const year = date2.getFullYear();
  const mon = String(date2.getMonth() + 1).padStart(2, '0');
  const day = String(date2.getDate()).padStart(2, '0');
  const hour = String(date2.getHours()).padStart(2, '0');
  const min = String(date2.getMinutes()).padStart(2, '0');
  const seconds = String(date2.getSeconds()).padStart(2, '0');
  const dateStr = year + mon + day + hour + min + seconds;
  return dateStr;
}

export function debounce<F extends (...args: any[]) => void>(
  func: F,
  wait: number,
): (v: any) => void {
  let timeout: ReturnType<typeof setTimeout> | null = null;
  return (v: any) => {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      func(v);
    }, wait);
  };
}

export function formatDate(date:Date): string {
  // 日期格式 yy-mm-dd hh:mm:ss
  const PoadToDigites = (num:number) =>{
    return num.toString().padStart(2,'0')
  }
  return `${date.getFullYear()}-${PoadToDigites(date.getMonth()+1)}-${PoadToDigites(date.getDate())} ${PoadToDigites(date.getHours())}:${PoadToDigites(date.getMinutes())}:${PoadToDigites(date.getSeconds())}`
}

export function handleWinBlank(centoslog:any) {
  const filelist = centoslog.centosResourceFilesList;
  let fileName = "";

  filelist?.map((item:any) => {
    if(item.fileName.substr(-4) === 'html') {
        fileName = item.fileName;
    }
  });

  const url = `${window.location.origin}/kylin-manager/kyreplace/replace_result/${fileName}`;

  window.open(url, "_blank");
}
